package com.ayz.gateway.core.core;

import com.alibaba.fastjson2.JSON;
import com.ayz.gateway.common.result.GatewayResult;
import io.netty.handler.codec.http.*;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;


/**
 * @ClassName HttpResponseParser
 * @Description TODO: 将网关的通用返回对象封装成HTTP响应的形式返回给客户端
 * @Author 快乐的星球
 * @Date 2023/5/10 17:43
 * @Version 1.0
 **/
public class HttpResponseParser {

    public static FullHttpResponse parse(GatewayResult gatewayResult){
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
        //设置响应体数据
        String bodyContent = JSON.toJSONString(gatewayResult);
        response.content().writeCharSequence(bodyContent, Charset.forName("UTF-8"));
        //响应头信息
        HttpHeaders headers = response.headers();
        //返回值类型
        headers.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + ";charset=UTF-8");
        //响应体长度
        headers.add(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        //配置长连接
        headers.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        //配置访问权限控制
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD, "GET,POST,PUT,DELETE");
        headers.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        return response;
    }
}
